package com.hqyj.emb.system.controller;

import com.hqyj.emb.system.model.Permission;
import com.hqyj.emb.system.model.User;
import frame.controller.BaseController2;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
@WebServlet("/loginController.do")
public class LoginController extends BaseController2 {
    public String login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName = req.getParameter("userName");
        String password = req.getParameter("password");
        User user= new User();
        user.setPassword(password);
        user.setUserName(userName);
        User user_db= (User) userService.queryAllUser(user);
        if(user_db!=null) {
            if (userName.equals(user_db.getUserName()) && password.equals(user_db.getPassword())) {
                // #######################查詢自己拥有的权限 ########################
                int userId = user_db.getUserId();
                // 1、登录用户信息ID,查询拥有的菜单
                List<Permission> firstLvMenuList = permissionService.queryUserRoleByUserId(userId);

                HashMap<Integer, List<Permission>> menuLvMap = new HashMap<>();

                for (Permission permission : firstLvMenuList) {
//                        System.out.println(permission);
                    //查询菜单下的权限集合：菜单ID等于权限父ID
                    int pId = permission.getPermissionId();
                    List<Permission> permissionSelectedListSon = permissionService.queryPermissionByPid(pId);
//                        for (Permission permission1 : permissionSelectedListSon) {
//                            System.out.println(permission1);
//                        }
                    // 维护父节点和子节点关系
                    menuLvMap.put(pId, permissionSelectedListSon);
                    //返回数据
                    req.setAttribute("firstLvMenuList", firstLvMenuList);
                    req.setAttribute("menuLvMap", menuLvMap);

                }
                return "view/frame/main.jsp";
            } else {
                return "index.jsp";
            }
        }else {
            return "index.jsp";
        }
    }
}
